class Snake {
  snake:HTMLElement
  head:HTMLElement
  snakeBody:HTMLCollection
  direction: string = 'left'
  constructor() {
    this.snake = document.getElementById('snake')!
    this.head = document.querySelector('#snake>div') as HTMLElement
    this.snakeBody = this.snake.getElementsByTagName('div')
  }
  get X() {
    return this.head.offsetLeft
  }
  get Y() {
    return this.head.offsetTop
  }
  set X(value:number){
    if(this.X === value) return  //关键代码！！使得蛇身体转向不会重叠 蛇只能在一个方向上移动
    if(value < 0 || value >390){
      throw new Error('蛇撞墙了！')
    }
    if(this.snakeBody[1] && (this.snakeBody[1] as HTMLElement).offsetLeft === value){
      if(value > this.X){
        // 说明蛇左走，向右调头
        value = this.X - 10
      } else {
        value = this.X + 10
      }
    }
    this.moveBody()
    this.head.style.left = value + 'px'
    this.isHitSelf()
  }
  set Y(value:number){
    if(this.Y === value) return  //关键代码！！使得蛇身体转向不会重叠 蛇只能在一个方向上移动
    if(value < 0 || value >390){
      throw new Error('蛇撞墙了！')
    }
    if(this.snakeBody[1] && (this.snakeBody[1] as HTMLElement).offsetTop === value){
      if(value > this.Y){
        // 说明蛇上走，向下调头
        value = this.Y - 10
      } else {
        value = this.Y + 10
      }
    }
    
    this.moveBody()
    this.head.style.top = value + 'px'
    this.isHitSelf()
  }

  addBody() {
    this.snake.insertAdjacentHTML('beforeend','<div></div>')
  }

  moveBody() {
    
    for(let i = this.snakeBody.length-1;i>0;i--){
      let X = (this.snakeBody[i-1] as HTMLElement).offsetLeft;
      let Y = (this.snakeBody[i-1] as HTMLElement).offsetTop;
      console.log(X,Y);
      
      
      (this.snakeBody[i] as HTMLElement).style.left = X + 'px';
      (this.snakeBody[i] as HTMLElement).style.top = Y + 'px';
    }
  }

  isHitSelf() {
    for(let i=1; i<this.snakeBody.length;i++){
      let X = (this.snakeBody[i] as HTMLElement).offsetLeft
      let Y = (this.snakeBody[i] as HTMLElement).offsetTop
      if(this.X === X && this.Y === Y){
        throw new Error('撞到自己了~')
      }
    }
  }
}
 

export default Snake